<?php
namespace app\lib\baidu;
use think\Db;

class Api 
{

    public function token(){
        $params = [
            'client_id'=>'YeyMF21dXex0vmVjUP5Z044G',
            'client_secret'=>'IoFoQbHWLmf0c8t9VGXM9baYqIOqfbD7',
            'grant_type'=>'client_credentials'
        ];
        $api_url = 'https://aip.baidubce.com/oauth/2.0/token';
        $result = httpRequest($api_url,$params,'POST',[
                'Content-Type: application/json',
                'Accept: application/json'
            ]);
        $result = json_decode($result,true);
        return $result;
    }

    public function chat($session_sn,$message){
        $token = $this->token();
        if (empty($token['access_token'])) {
            return ['status'=>0,'msg'=>$token['error_description']];
        }
        $access_token = $token['access_token'];
        $messages = [];
        $api_url = 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token='.$access_token;

        $map = [
            ['session_sn','=',$session_sn]
        ];
        $msgs = Db::name('msg')->field('message,reply')->where($map)->order('id','desc')->limit(3)->select();
        // for($i = count($msgs) - 1;$i >= 0;$i--){
        for($i = 0;$i < count($msgs);$i++){
            $messages[] = [
                'role'=>'user',
                'content'=>$msgs[$i]['message']
            ];
            $messages[] = [
                'role'=>'assistant',
                'content'=>$msgs[$i]['reply']
            ];
        }
        $messages[] = [
            'role'=>'user',
            'content'=>$message
        ];

        if (count($messages) > 1 && count($messages) % 2 == 0) {
            array_shift($messages);
        }
        $params = [
            'messages'=>$messages
        ];
        $result = httpRequest($api_url,json_encode($params,JSON_UNESCAPED_UNICODE),'POST',[
                'Content-Type: application/json',
                'Accept: application/json'
            ]);
        Db::name('test')->insert(['content'=>$result]);
        Db::name('test')->insert(['content'=>json_encode($params,JSON_UNESCAPED_UNICODE)]);
        
        $result = json_decode($result,true);
        // dump($params);
        // dump($result);die;
        if ( !empty($result['result']) ) {
            if ( $result['usage']['completion_tokens'] > 0 ) {
                return ['status'=>1,'answer'=>$result['result']];
            }else{
                return ['status'=>2,'answer'=>$result['result']];
            }
        }else{
            return ['status'=>0,'msg'=>$result['error_msg']];
        }
    }
   
}
